package org.jeecg.modules.lock.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.modules.lock.service.LwgyDoorLockService;
import org.jeecg.modules.lock.service.impl.LwgyDoorLockServiceImpl;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA
 *
 * @Description:
 * @Author : M-JGG
 * @create 2024/4/2 15:04
 */
@Api(tags="门锁-设置回调地址")
@RestController
@RequestMapping("/doorLock")
@Slf4j
public class LwgyDoorLockController{

    private static final String CALLBACK_URL_SET_ENDPOINT = "https://server.hxjiot.com";// 接口地址

    @AutoLog(value = "门锁-设置回调地址")
    @ApiOperation(value="门锁-设置回调地址",notes = "门锁-设置回调地址")
    @PostMapping(value = "/setCallbackUrl")
    public boolean setCallbackUrl() {
        try {
            // 获取tokenId
            LwgyDoorLockService doorLockService = new LwgyDoorLockServiceImpl();
            String tokenId = doorLockService.getAuthentication();
            System.out.println("tokenId ========== " + tokenId);
            if (tokenId == null) {
                System.out.println("获取tokenId失败");
                return false;
            }
            OkHttpClient client = new OkHttpClient();
            MediaType mediaType = MediaType.parse("application/json; charset=utf-8");

            // 构建请求体
            String callbackUrl = "http://119.45.62.71:8081/ihome/belongDoorLock/receiveDoorLockData"; // 回调地址
            Map<String, Object> requestData = new HashMap<>();
            requestData.put("callbackurl", callbackUrl);

            Map<String, Object> requestBodyMap = new HashMap<>();
            requestBodyMap.put("method", "apartmentCallBackUrlSet");
            requestBodyMap.put("tokenId", tokenId);
            requestBodyMap.put("data", requestData);
            System.out.println("requestBodyMap == " + requestBodyMap);

            ObjectMapper objectMapper = new ObjectMapper();
            String requestBody = objectMapper.writeValueAsString(requestBodyMap);
            System.out.println("requestBody == " + requestBody);
            RequestBody body = RequestBody.create(mediaType, requestBody);

            // 构建请求
            Request request = new Request.Builder()
                    .url(CALLBACK_URL_SET_ENDPOINT)
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Content-Version", "1.1")
                    .build();

            // 发起请求
            Response response = client.newCall(request).execute();

            if (response.isSuccessful()) {
                // 解析响应
                String jsonResponse = response.body().string();
                Map<String, Object> data = objectMapper.readValue(jsonResponse, new TypeReference<HashMap<String, Object>>() {});

                System.out.println("data ========== " + data);
                // 检查结果码
                int resultCode = (int) data.get("resultCode");
                System.out.println("resultCode ========== " + resultCode);
                String method = (String) data.get("method");
                System.out.println("method ========== " + method);
                if (resultCode == 0) {
                    System.out.println("回调地址设置成功");
                    return true;
                } else {
                    String reason = (String) data.get("reason");
                    System.out.println("回调地址设置失败: " + reason);
                    return false;
                }
            } else {
                System.out.println("设置回调地址接口调用失败: " + response.message());
                return false;
            }
        } catch (Exception e) {
            System.out.println("调用设置回调地址接口报错: " + e.getMessage());
            return false;
        }
    }
}
